# coding: utf-8

from django import template
from shared_accounting.models import Deposit, Draw, Pay, DepositAndPay, Transfer

register = template.Library()

@register.filter
def dm_percent(value, member):
    return value.get('dm_percent_%s' % member.id, '')

@register.filter
def dm_number(value, member):
    return value.get('dm_number_%s' % member.id, '')

@register.filter
def format_time(time):
    current = tz.local_now()
    #logging.info('time: %s, current: %s' % (time, current))
    delta = current - local_time(time)
    if delta.days > 0:
        if delta.days <= 30:
            return u'%s天前' % delta.days
        else:
            #localtime = time + datetime.timedelta(0, 8*3600)
            return time.strftime(u'%y年%m月%日')
    else:
        if delta.seconds < 60:
            return u'刚刚'
        elif delta.seconds < 3600:
            return u'%s分钟前' % (delta.seconds/60)
        else:
            return u'%s小时前' % (delta.seconds/3600)


@register.inclusion_tag('incl/form.html')
def render_form(form):
    return {
        'form': form,
    }

@register.inclusion_tag('incl/field.html')
def render_field(field):
    return {
        'field': field,
    }

@register.filter
def get_tranc_disp_name(tranc):
    if isinstance(tranc, Deposit):
        return u'存款'
    elif isinstance(tranc, Draw):
        return u'取款'
    elif isinstance(tranc, DepositAndPay):
        return u'垫付'
    elif isinstance(tranc, Pay):
        return u'支付'
    elif isinstance(tranc, Transfer):
        return u'转账'
    else:
        return u'未知交易'

@register.filter
def disp_member_account(tranc):
    if isinstance(tranc, (Deposit, Draw, DepositAndPay)):
        return tranc.member.name
    elif isinstance(tranc, Transfer):
        return u'%s 到 %s' % (tranc.member.name, tranc.to_member.name)
    else:
        return '-'

@register.filter
def get_tranc_type(tranc):
    if isinstance(tranc, DepositAndPay):
        return 'dpay'
    else:
        return tranc.__class__.__name__.lower()

from shared_accounting.forms import DIST_MODE_CHOICES
@register.filter
def dist_mode_name(mode):
    for k, v in DIST_MODE_CHOICES:
        if k == mode:
            return v
    return ''

@register.filter
def member_amount(account, user):
    for member in account.get_members():
        if member.user.id == user.id:
            return member.amount
    return ''

from shared_accounting import tz
local_time = register.filter(tz.local_time)
